package com.qf.fmall2204.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.fmall2204.constants.Constants;
import com.qf.fmall2204.user.entity.User;
import com.qf.fmall2204.user.mapper.UserMapper;
import com.qf.fmall2204.user.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.fmall2204.utils.SaltUtils;
import com.qf.fmall2204.vo.UserRegistVo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotBlank;
import java.util.Date;

/**
 * <p>
 * 用户  服务实现类
 * </p>
 *
 * @author dong
 * @since 2023-04-20
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    public static void main(String[] args) {
        UserServiceImpl userService = new UserServiceImpl();
        userService.regist(null);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void regist(UserRegistVo userRegistVo) {

        //1. 检查当前用户名是否已经存在，存在抛异常
        String username = userRegistVo.getUsername();
        User dbuser = this.getOne(new QueryWrapper<User>().eq("username", username));
        if (dbuser!=null){
            throw new RuntimeException("用户名已经存在了，注册失败");
        }

        //2. 处理密码 md5加密
        String password = userRegistVo.getPassword();
        String salt = SaltUtils.genSalt(Constants.SALT_LENTH);
        String md5password = new Md5Hash(password, salt, Constants.HASH_TIMES).toHex();

        //3. 入库
        User user = new User();
//        BeanUtils.copyProperties(userRegistVo,user);
        user.setUsername(userRegistVo.getUsername());
        user.setPassword(md5password);
        user.setUserRegtime(new Date());
        user.setUserModtime(new Date());
        user.setSalt(salt);
        this.save(user);

    }
}
